<template>
  <el-dialog v-model="visible" :append-to-body="true" :draggable="true" width="650px" title="选择联系人" custom-class="user-contacts">
    <el-container class="lum-dialog-box" v-outside="close">
      <el-main class="main no-padding">
        <el-container class="full-height">
          <el-aside width="250px" class="aside-border">
            <el-container class="full-height no-select">
              <el-header
                class="no-padding search-header"
                :class="{ shadow: headerShadow }"
                height="50px"
              >
                <el-input
                  v-model="keywords"
                  clearable
                  size="default"
                  placeholder="搜索 | 好友 or 群组"
                  :prefix-icon="Search"
                />
              </el-header>
              <el-main class="no-padding">
                <el-scrollbar
                  ref="scrollbar2"
                  class="full-height"
                  tag="section"
                  :native="false"
                >
                  <ul class="friend-items no-select">
                    <li
                      v-for="item in search"
                      :key="item.index_name"
                      @click="triggerContacts(item)"
                    >
                      <el-avatar
                        class="avatar"
                        style="margin-top: 5px"
                        :size="25"
                        :src="item.avatar"
                      >
                        <img :src="detaultAvatar" />
                      </el-avatar>
                      <span class="nickname">
                        [{{ item.type == 1 ? '友' : '群' }}] {{ item.nickname }}
                      </span>
                      <span class="select-btn">
                        <el-icon :class="{ 'i-color-green': item.checked }"><ele-SuccessFilled /></el-icon>
                      </span>
                    </li>
                  </ul>
                </el-scrollbar>
              </el-main>
            </el-container>
          </el-aside>

          <el-main class="no-padding">
            <el-container class="full-height">
              <el-header height="40px">
                <el-divider class="no-select" content-position="left">
                  <span style="color: #c4c5c7">
                    已选联系人 ({{ selected.length }})
                  </span>
                </el-divider>
              </el-header>
              <el-main>
                <el-scrollbar :native="false" tag="section" class="full-height">
                  <div class="selectd-items">
                    <div
                      v-for="item in selected"
                      :key="item.index_name"
                      class="selectd-item no-select"
                    >
                      <el-avatar :size="25" :src="item.avatar">
                        <img :src="detaultAvatar" />
                      </el-avatar>
                      <p>{{ item.nickname }}</p>
                      <div
                        class="triangle-topleft"
                        :class="{ group: item.type == 2 }"
                      ></div>
                      <div class="del-mask" @click="delContacts(item)">
                        <el-icon><ele-Delete /></el-icon>
                      </div>
                    </div>
                  </div>
                </el-scrollbar>
              </el-main>
            </el-container>
          </el-main>
        </el-container>
      </el-main>
      <el-footer height="50px" class="no-padding footer">
        <el-button size="default" plain @click="close">取消</el-button>
        <el-button type="primary" size="default" @click="confirm">
          确认选择<span v-show="selected.length">({{ selected.length }})</span>
        </el-button>
      </el-footer>
    </el-container>
  </el-dialog>
</template>

<script>
import { computed, reactive, ref, toRefs, watch, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import detaultAvatar from '/@/assets/detault-avatar.jpg'
import { useChatApi } from '/@/api/chat/index'

export default {
    name: 'UserContacts',
    props: {
      show: {
        type: Boolean,
        default: false
      }
    },
    emits: ['update:show', 'confirm'],
    setup(props, context) {
        const { show } = toRefs(props)
        const chatApi = useChatApi()
        const scrollbar2 = ref()
        const state = reactive({
          contacts: [],
          search: [],
          keywords: '',
          headerShadow: false
        })
        const selected = computed(() => {
          return state.contacts.filter(item => item.checked)
        })
        const visible = computed({
            get: () => show.value,
            set: val => {
              context.emit('update:show', val)
            }
        })
        //触发选择联系人事件
        const triggerContacts = (item) => {
            let index = state.contacts.findIndex(val => {
                return val.index_name == item.index_name
            })
            state.contacts[index].checked = !state.contacts[index].checked
        }
        //取消选中的联系人
        const delContacts = (item) => {
            let index = state.contacts.findIndex(val => {
                return val.index_name == item.index_name
            })
            state.contacts[index].checked = false
        }
        //移除所有选中选项
        const delAll = () => {
          state.contacts.forEach((item, i) => {
            state.contacts[i].checked = false
          })
        }
        //关闭窗口
        const close = (e) => {
          delAll()
          context.emit('update:show', false)
          e.stopPropagation();
        }
        //确认按钮点击事件
        const confirm = () => {
          const arr = selected.value.map(item => ({
            id: item.id,
            type: item.type,
          }))
          context.emit('confirm', arr)
        }
        //加载好友列表
        const loadFriends = () => {
          chatApi.ServeGetContacts().then(res => {
              if (res.code == 0) {
                  const items = res.data.items
                  for (let o of items) {
                      state.contacts.push({
                        id: o.id,
                        type: 1,
                        index_name: `1_${o.id}`,
                        nickname: o.friend_remark ? o.friend_remark : o.nickname,
                        avatar: o.avatar,
                        checked: false
                      })
                  }
                  state.search = state.contacts.filter(item => {
                      return item.nickname.match(state.keywords) != null
                  })
              }
          })
        }
        //加载群聊列表接口
        const loadUserGroups = () => {
            chatApi.ServeGetGroups().then(res => {
                if (res.code == 0) {
                    for (let o of res.data.rows) {
                        state.contacts.push({
                            id: o.id,
                            type: 2,
                            index_name: `2_${o.id}`,
                            nickname: o.group_name,
                            avatar: o.avatar,
                            checked: false,
                        })
                    }
                }
            })
        }
        // 监听自定义滚动条事件
        const scrollEvent = () => {
          if(!scrollbar2.value) return 
          let scrollbarEl = scrollbar2.value.wrap$
          scrollbarEl.onscroll = () => {
            state.headerShadow = scrollbarEl.scrollTop > 0
          }
        }
        watch(() => state.keywords,
          val => {
            if (val == '') {
              state.search = state.contacts
            } else {
              state.search = state.contacts.filter(item => {
                  return item.nickname.match(state.keywords) != null
              })
            }
          }
        )
        watch(() => state.contacts,
          arr => {
            if (state.keywords == '') {
              state.search = arr
            }
          }
        )
        onMounted(() => {
          loadFriends()
          loadUserGroups()
          scrollEvent()
        })
        return {
            ...toRefs(state),
            Search,
            detaultAvatar,
            selected,
            scrollbar2,
            triggerContacts,
            delContacts,
            delAll,
            close,
            confirm,
            loadFriends,
            loadUserGroups,
            scrollEvent,
            visible
        }
    }
}
</script>

<style lang="scss" scoped>
:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}

.lum-dialog-box {
  width: 650px;
  max-width: 650px;
  height: 550px;

  .main {
    .aside-border {
      border-right: 1px solid #f5eeee;
    }
  }

  .footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-right: 10px;
    border-top: 1px solid #f5eeee;
  }
}

.search-header {
  padding: 8px;
  display: flex;
  justify-content: center;
  align-items: center;

  &.shadow {
    box-shadow: 0 2px 6px 0 rgba(31, 35, 41, 0.05);
  }
}

.friend-items {
  li {
    padding: 10px;
    cursor: pointer;
    position: relative;

    &:hover {
      background: #f5f5f5;
    }

    .avatar {
      margin-top: 3px;
    }

    .nickname {
      width: 60%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      position: absolute;
      top: 10px;
      left: 52px;
      height: 35px;
      line-height: 35px;
      font-weight: 400;
      font-size: 13px;
    }

    .select-btn {
      position: absolute;
      width: 32px;
      height: 35px;
      right: 3px;
      top: 10px;
      line-height: 35px;
      text-align: center;

      i {
        color: #ccc;
      }

      .i-color-green {
        color: var(--el-color-primary) !important;
      }
    }
  }
}

.group-from {
  label {
    height: 45px;
    line-height: 47px;
    width: 50px;
    color: #606266;
    padding-right: 3px;
    font-size: 13px;
  }

  input {
    height: 25px;
    width: 100%;
    text-indent: 3px;
    color: #a9a4a4;
    font-size: 12px;
    border-bottom: 1px solid #efebeb;
  }
}

.selectd-items {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-items: flex-start;

  .selectd-item {
    width: 23%;
    height: 65px;
    margin: 6px 2px 0px 2px;
    cursor: pointer;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    box-shadow: 0px 0px 3px 0 rgba(0, 0, 0, 0.1);

    .triangle-topleft {
      width: 0;
      height: 0;
      border-top: 15px solid var(--el-color-primary);
      border-right: 15px solid transparent;
      position: absolute;
      top: 0;
      left: 0;
      &.group {
        border-top: 15px solid #ff9800;
      }
    }

    p {
      width: 90%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 10px;
      margin-top: 8px;
      text-align: center;
    }

    .del-mask {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(31, 35, 41, 0.5);
      display: none;
      justify-content: center;
      align-items: center;
      color: white;
      transition: ease 0.5s;
      border-radius: 2px;
    }

    &:hover .del-mask {
      display: flex;
    }
  }
}
</style>
<style lang="scss">
.el-overlay .el-overlay-dialog .user-contacts{
  .el-dialog__body{
    padding: 0 !important;
  }
}
</style>